package io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

@Slf4j
public class BIOServer {

    public static void main(String[] args) throws IOException {
        // 创建一个ServerSocket，监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        log.info("服务器启动成功，监听端口：{}", serverSocket.getLocalPort());

        while (true) {
            // 等待客户端连接
            Socket socket = serverSocket.accept();
            log.info("客户端[{}]已连接", socket.getRemoteSocketAddress());

            // 创建线程处理客户端请求  这里会有问题，当客户端连接多了之后，会创建很多线程，导致服务器崩溃
            new Thread(new SingleHandler(socket)).start();
        }
    }

    static class SingleHandler implements Runnable {

        private final Socket socket;

        public SingleHandler(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                // 从客户端获取链接
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                while (true) {
                    // inputStream转成字符串  这里也会有问题，如果客户端发送的消息过长，服务器会一直等待，导致服务器崩溃
                    Scanner scanner = new Scanner(inputStream);
                    String msg = scanner.nextLine();
                    log.info("收到客户端消息：{}", msg);

                    // 回复客户端
                    PrintWriter printWriter = new PrintWriter(outputStream, true);
                    printWriter.println("你好，客户端");
                    log.info("回复客户端消息：{}", "你好，客户端");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
